package com.michale.framework.config.async.manager;

import com.michale.common.utils.async.ThreadUtils;
import com.michale.common.utils.spring.SpringUtils;
import io.swagger.annotations.ApiModelProperty;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.annotation.PreDestroy;
import java.util.TimerTask;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * @author Michale
 * @apiNote 异步任务管理器
 */
@Component
public class AsyncManager {

    private static final Logger log = LoggerFactory.getLogger("关闭后台");
    @ApiModelProperty("操作延迟10毫秒")
    private final int OPERATE_DELAY_TIME = 10;

    private ScheduledExecutorService executor = SpringUtils.getBean("scheduledExecutorService");


    public AsyncManager() {
    }

    private static AsyncManager annotations = new AsyncManager();

    public static AsyncManager asyncManager() {
        return annotations;
    }


    /**
     * 执行异步任务
     *
     * @param timerTask
     * @return
     * @throws Exception
     */
    public void start(TimerTask timerTask)  {
        executor.schedule(timerTask, OPERATE_DELAY_TIME, TimeUnit.MILLISECONDS);
    }

    /**
     * 停止任务线程池
     * 确保应用退出时能关闭后台线程(对象销毁时执行)
     *
     * @throws Exception
     */
    @PreDestroy
    public void stop()  {
        try {
            ThreadUtils.shutdownAndAwaitTermination(executor);
            log.info("====关闭后台任务任务线程池====");
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
    }

}
